import { Component, OnInit } from '@angular/core';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { ApiService } from '@core/services/http/api.service';
import { BiService } from '../../../bi.service';
import { ApesModalService } from '@shared/apes/modal';
import { TechnicalReviewDialogComponent } from './technical-review-dialog.component';
import { dateFormat } from '../../../../../utils/utils';

@Component({
  selector: 'technical-review',
  templateUrl: './technical-review.component.html',
  styleUrls: ['./technical-review.component.scss'],
})
export class TechnicalReviewComponent implements OnInit {

  // 技术审核分析

  // 效率
  efficiencyOption: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['单量', '超时', '平均耗时'],
    },
    xAxis: {
      type: 'category',
    },
    yAxis: [
      {
        name: '单量',
        type: 'value',
        axisLabel: {
          formatter: '{value} 单',
        },
      },
      {
        name: '耗时',
        type: 'value',
        axisLabel: {
          formatter: '{value} 分钟',
        },
      },
    ],
    series: [
      { name: '单量', type: 'bar' },
      { name: '超时', type: 'bar' },
      { name: '平均耗时', type: 'line', yAxisIndex: 1 },
    ],
  };
  efficiencyField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  efficiencyData: any;
  efficiencyModel: any = {};
  efficiencyLoading: boolean = false;

  // 贡献榜
  staffField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'month',
        },
        divCol: 5,
      },
    },
  ];
  staffData: any;
  staffModel: any = {};
  staffLoading: boolean = false;

  // 贡献漏斗
  contributionOption: any = {
    series: [
      {
        name: '漏斗图',
        type: 'funnel',
        left: '0%',
        top: 40,
        bottom: 100,
        width: '60%',
        min: 0,
        max: 100,
        minSize: '0%',
        maxSize: '100%',
        sort: 'descending',
        gap: 2,
        label: {
          show: true,
          // position: 'inside'
        },
        labelLine: {
          length: 80,
        },
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 1,
        },
        emphasis: {
          label: {
            fontSize: 24,
          },
        },
        data: [
          { value: 25, name: '方案收款单数' },
          { value: 50, name: '方案确认数' },
          { value: 75, name: '技术审核通过单数' },
          { value: 100, name: '技术审核总单数' },
        ],
      },
    ],
  };
  contributionField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  contributionData: any;
  contributionModel: any = {};
  contributionLoading: boolean = false;

  // 转化统计
  // 单数
  conversionOption: any = {
    title: {
      subtext: '单数统计',
      left: 'left',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['技术审核总单数', '技术审核通过单数', '方案确认单数', '方案收款单数'],
    },
    xAxis: { type: 'category' },
    yAxis: {},
    series: [
      { name: '技术审核总单数', type: 'line' },
      { name: '技术审核通过单数', type: 'line' },
      { name: '方案确认单数', type: 'line' },
      { name: '方案收款单数', type: 'line' },
    ],
  };
  conversionField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  conversionData: any;
  conversionModel: any = {};
  conversionLoading: boolean = false;

  // 金额
  amountOption: any = {
    title: {
      subtext: '金额统计',
      left: 'left',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['技术审核总金额', '技术审核通过金额', '方案确认金额', '方案收款金额'],
    },
    xAxis: { type: 'category' },
    yAxis: {},
    series: [
      { name: '技术审核总金额', type: 'line' },
      { name: '技术审核通过金额', type: 'line' },
      { name: '方案确认金额', type: 'line' },
      { name: '方案收款金额', type: 'line' },
    ],
  };
  amountData: any;
  amountLoading: boolean = false;

  // 退回统计
  returnOption: any = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['退回单数'],
    },
    xAxis: { type: 'category' },
    yAxis: { name: '单数' },
    series: [
      { name: '退回单数', type: 'line' },
    ],
  };
  returnField: FormlyFieldConfig[] = [
    {
      key: 'DATE',
      type: 'conditionInput',
      templateOptions: {
        label: '统计时间',
        config: {
          operators: ['EQ'],
          type: 'monthRange',
        },
        divCol: 5,
      },
    },
  ];
  returnData: any;
  returnModel: any = {};
  returnLoading: boolean = false;

  constructor(
    private apiService: ApiService,
    private bi: BiService,
    private modalService: ApesModalService,
  ) {

  }

  ngOnInit() {
    setTimeout(() => {
      this.refreshEfficiencyData();
      this.refreshStaffData();
      this.refreshContributionData();
      this.refreshConversionData();
      this.refreshReturnData();
    }, 1000);
  }

  refreshEfficiencyData() {
    let date = this.bi.conversionMonths(this.efficiencyModel['DATE'], 6);

    const data = {
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let api = 'fn.tech.qryTechDiagramm';

    this.efficiencyLoading = true;
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
      console.log('效率统计', body);
      // let dimensions = ['mouth'];
      let source = [['mouth','greenModul','redModul','lineModul']];
      if (body && body.length != 0) {
        body.forEach((res) => {
          // dimensions.push(res['mouth']);
          source.push([
            res['mouth'],
            res['greenModul'],
            res['redModul'],
            res['lineModul'],
          ]);

        });
      }
      this.efficiencyData = {
        dataset: {
          // dimensions: dimensions,
          source: source,
        },
      };
      this.efficiencyLoading = false;
    });
  }

  refreshStaffData() {
    let date = this.bi.conversionMonth(this.staffModel['DATE']);

    let nowMonth = date.getMonth(); //当前月
    let nowYear = date.getFullYear(); //当前年
    let startDate = new Date(nowYear, nowMonth, 1);
    let endDate: Date = new Date(nowYear, nowMonth + 1, 0, 23, 59, 59);
    let dateItem = [
      dateFormat('yyyy-MM-ddT', startDate) + '00:00:00.000Z',
      dateFormat('yyyy-MM-ddT', endDate) + '23:59:59.000Z',
    ];

    const data = {
      DATE_START: dateItem[0],
      DATE_END: dateItem[1],
    };


    let api = 'fn.tech.mouthTechAudit';

    this.staffLoading = true;
    this.staffData = [];
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
      console.log('月度贡献榜', body);
      if (body && body.length != 0) {
        this.staffData = body;
      }
      this.staffLoading = false;
    });
  }

  showStaffText(oldT, newT, type = false) {
    let showText = '--';
    if (oldT && oldT != '--') {
      let t;
      if (oldT > newT) {
        t = oldT - newT;
      } else if (oldT < newT) {
        t = newT - oldT;
      } else {
        t = '--';
      }
      if (type && t != '--') {
        showText = t.toFixed(2);
      } else {
        showText = t;
      }
    }
    return showText;
  }

  showStaffClass(oldT, newT) {
    let showClass = 'noChange';
    if (oldT && oldT != '--') {
      if (oldT > newT) {
        showClass = 'showDown';
      } else if (oldT < newT) {
        showClass = 'showUp';
      } else {
        showClass = 'noChange';
      }
    }
    return showClass;
  }

  refreshContributionData() {
    let date = this.bi.conversionMonths(this.contributionModel['DATE'], 6);

    const data = {
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let api = 'fn.tech.qryTechLeak';

    this.contributionData = [];
    this.contributionLoading = true;
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('贡献漏斗统计', body);
      if (body && body.length != 0) {
        this.contributionData = body;
      }
      this.contributionLoading = false;
    });
  }

  showPercentage(current, main, index) {
    let preIndex = index - 1;
    if (preIndex < 0) return '--';
    let pre = main[preIndex].AMOUNT;
    let show = (current / pre) * 100;
    return show.toFixed(2) + '%';
  }

  refreshConversionData() {
    let date = this.bi.conversionMonths(this.conversionModel['DATE'], 6);

    const data = {
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let conversionApi = 'fn.tech.qryLineCharAmout';

    this.conversionLoading = true;

    this.apiService.post(conversionApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('转化统计-单数', body);
      // let dimensions = [];
      let source = [['mouth','line1','line2','line3','line4']];
      if (body && body.length != 0) {
        body.forEach((res) => {
          // dimensions.push(res['mouth']);
          source.push([
            res['mouth'],
            res['line1'],
            res['line2'],
            res['line3'],
            res['line4'],
          ]);

        });
      }
      this.conversionData = {
        dataset: {
          // dimensions: dimensions,
          source: source,
        },
      };
      this.conversionLoading = false;
    });

    let amountApi = 'fn.tech.qryLineCharMoney';

    this.amountLoading = true;

    this.apiService.post(amountApi, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('转化统计-金额', body);
      if (body && body.length != 0) {
        // let dimensions = [];
        let source = [['mouth','line1','line2','line3','line4']];
        body.forEach((res) => {
          // dimensions.push(res['mouth']);
          source.push([
            res['mouth'],
            res['line1'],
            res['line2'],
            res['line3'],
            res['line4'],
          ]);

        });
        this.amountData = {
          dataset: {
            // dimensions: dimensions,
            source: source,
          },
        };

      }
      this.amountLoading = false;
    });
  }

  refreshReturnData() {
    let date = this.bi.conversionMonths(this.returnModel['DATE'], 6);

    const data = {
      DEPT_ID: [],
      DATE_START: date[0],
      DATE_END: date[1],
    };

    let api = 'fn.tech.qryBackPriceAudit';

    this.returnLoading = true;
    this.apiService.post(api, { 'body': JSON.stringify(data) }).subscribe((body) => {
      // console.log('退回统计', body);
      // let dimensions = [];
      let source = [['mouth','AMOUNT']];
      if (body && body.length != 0) {
        body.forEach((res) => {
          // dimensions.push(res['mouth']);
          source.push([
            res['mouth'],
            res['AMOUNT'],
          ]);

        });
      }
      this.returnData = {
        dataset: {
          // dimensions: dimensions,
          source: source,
        },
      };
      this.returnLoading = false;
    });
  }

  openDialog() {
    let dialog;
    const openDialog = dialog ? dialog : TechnicalReviewDialogComponent;
    const dialogRef = this.modalService.create({
      apesWidth: '70vw',//1200
      // apesMaskClosable: false,
      apesTitle: '技术审核退回原因',
      apesContent: openDialog,
      apesComponentParams: {},
    });
  }

}

